/*
 * commons is a based project implemented
 * Copyright (C) 2024 Jasmine
 */
package com.commons.log.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;

import com.commons.core.utils.ContextHolder;
import com.commons.ip.utils.IpUtil;
import com.commons.log.domain.LogRecord;

import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import jakarta.servlet.http.HttpServletRequest;

/**
 * 系统日志工具类
 *
 * @author Jasmine
 * @version 1.0
 * @date 2020/12/16 16:35
 * @see SysLogUtils
 * @since JDK1.8
 */
public class SysLogUtils {

    public static LogRecord getSysLog() {

        LogRecord sysLogDTO = new LogRecord();
        sysLogDTO.setType(LogTypeEnum.NORMAL.getType());
        try {
            HttpServletRequest httpRequest = ContextHolder.getHttpRequest();

            String ip = IpUtil.getRemoteIP(httpRequest);
            sysLogDTO.setIp(ip);
            sysLogDTO.setIpAddress(IpUtil.getAddress(ip));

            String userAgentString = httpRequest.getHeader(HttpHeaders.USER_AGENT);
            if (StringUtils.isBlank(userAgentString)) {
                userAgentString = httpRequest.getHeader(HttpHeaders.USER_AGENT.toLowerCase());
            }
            if (StringUtils.isNotBlank(userAgentString)) {
                // 登录设备
                sysLogDTO.setUserAgent(userAgentString);

                // 解析agent字符串
                UserAgent userAgent = UserAgent.parseUserAgentString(userAgentString);
                // 获取操作系统对象
                OperatingSystem operatingSystem = userAgent.getOperatingSystem();
                // 获取浏览器对象
                Browser browser = userAgent.getBrowser();

                sysLogDTO.setBrowser(browser.getGroup().getName() + ":" + userAgent.getBrowserVersion());
                sysLogDTO.setOs(operatingSystem.getName());
            }

            sysLogDTO.setRequestUri(httpRequest.getRequestURI());
            sysLogDTO.setRequestMethod(httpRequest.getMethod());
        } catch (Exception e) {
        }
        return sysLogDTO;
    }
}
